package org.sjtc.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

public class SjtcServer {

    private int port = 9999;

    public SjtcServer() {
    }

    public SjtcServer(Integer port) {
        this.port = port;
    }

    public void run() {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    // socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,
                    //         Unpooled.wrappedBuffer("]".getBytes())));
                    // socketChannel.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,
                    //         3, 2, -3, 7));
                    // socketChannel.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,
                    //         15, 4, 2, 0));
                    // socketChannel.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,
                    //         15, 4, 2, 0)); // 重要
                    socketChannel.pipeline().addLast(new MyLengthFieldBasedFrameDecoder(Integer.MAX_VALUE,
                            15, 4, 2, 0)); // 重要
                    // socketChannel.pipeline().addLast(new MyDecoder());
                    socketChannel.pipeline().addLast(new StringDecoder());
                    socketChannel.pipeline().addLast(new ReturnMsgFrameEncode());
                    socketChannel.pipeline().addLast(new ServerReceiveHandler());
                }
            })
            .option(ChannelOption.SO_BACKLOG, 1024)
            .childOption(ChannelOption.SO_KEEPALIVE, true);
            System.out.println("服务启动成功,端口号:" + this.port);
            serverBootstrap.bind(this.port).sync().channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
